package com.duke.payphone.sell;

import java.io.Serializable;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.duke.payphone.Global;
import com.duke.payphone.LoginActivity;
import com.duke.payphone.R;
import com.duke.payphone.ServerPortal;
import com.duke.payphone.factory.MapFactory;


/**
 * activity responsible for displaying the QR image.. (pull the image from
 * globalvars)
 * 
 * 
 * during this activity, (ideally app would wait for push notification)
 * the activity will poll the server to wait until transaction has been
 * processed
 * 
 * server returns valid (and transcation info - story this in globalvars),
 * proceed to "SellComplete" activity
 * 
 * server returns invalid (due to server timeout, or other fail), transaction is
 * deleted
 * toast = "transaction failed", return to ROOT activity
 * 
 * 
 * <DEPRECATED>
 * press cancel:
 * displays pop-up screen to confirm cancel of transaction
 * if yes, send request to server to cancel the transaction, if server says
 * okay, toast = 'transaction canceled'
 * if yes, and server says no, toast = 'server error' - transaction will be
 * canceled on server timeout
 * return to ROOT activity
 * if no, remove popup
 * 
 * buttons: Cancel (to cancel the transaction)
 * </DEPRECATED>
 * 
 * @author Michael
 * 
 */
public class SellQRActivity extends Activity {

    // SET THIS:
    private final int timerlength = 1000; // length of timer

    private Global globalvars;
    private int counter = 0; // timer loop
    private boolean breakLoop = false;

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sell_qr);

        globalvars = (Global) getApplicationContext();
        ImageView image = (ImageView) findViewById(R.id.image_qr);
        counter = 0;
        breakLoop = false;

        Bundle extras = getIntent().getExtras();
        byte[] b = extras.getByteArray("qrcode");

        Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
        image.setImageBitmap(bmp);
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        // getMenuInflater().inflate(R.menu.activity_sell_qr, menu);
        // return true;
        return false;
    }

    /**
     * polls the server to find state of transaction
     * 
     * @param v
     */
    public void executeDone (View v) {

        // polling loop
        while (counter < timerlength) {
            counter++;
            System.out.println("App polling counter at: " + counter);

            if ((counter % 50) == 0) {
                executePoll();
            }

            if (breakLoop) {
                break;
            }
        }

        if (!breakLoop) {
            // polling loop failed
            Toast.makeText(globalvars, "Transaction timed-out. Canceling...", Toast.LENGTH_SHORT)
                    .show();
        }

        finish();
    }

    /**
     * @param v
     */
    private void executePoll () {

        // create request map
        Map<String, Serializable> request = MapFactory.createTransmitMap("sellpoll");

        if (true) {

            // send to server
            Map<String, Serializable> response = ServerPortal.contactServer(request);

            // wait for reply
            if (response.containsKey("server") && response.get("server").equals("valid")) {

                if (response.containsKey("session") && response.get("session").equals("valid")) {

                    if (response.containsKey("result") && response.get("result").equals("valid")) {
                        onSellPollValid(response);
                    }
                    else {
                        onSellPollInvalid(response);
                    }
                }
                else {
                    onSessionInvalid();
                }
            }
            else {
                onServerInvalid();
            }
        }
    }

    /**
     * @param response
     */
    private void onSellPollValid (Map<String, Serializable> response) {

        breakLoop = true;

        Toast.makeText(globalvars, "Transaction successful.", Toast.LENGTH_SHORT).show();

        Intent toSellComplete = new Intent(this, SellCompleteActivity.class);

        if (response.containsKey("productname")) {
            toSellComplete.putExtra("productname", (String) response.get("productname"));
        }
        if (response.containsKey("price")) {
            toSellComplete.putExtra("price", (String) response.get("price"));
        }
        if (response.containsKey("date")) {
            toSellComplete.putExtra("date", (String) response.get("date"));
        }

        if (response.containsKey("seller")) {
            toSellComplete.putExtra("seller", (String) response.get("seller"));
        }

        if (response.containsKey("buyer")) {
            toSellComplete.putExtra("buyer", (String) response.get("buyer"));
        }

        startActivity(toSellComplete);
        finish();

    }

    /**
     * @param response
     */
    private void onSellPollInvalid (Map<String, Serializable> response) {

        // NOTHING
        System.out.println("poll invalid");
    }

    /**
     * If server has timed out
     */
    private void onServerInvalid () {
        // toast: server error, please verify server connection and retry
        // request
        Toast.makeText(globalvars, "Server/network error. Please retry.", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * If session has timed out
     */
    private void onSessionInvalid () {
        breakLoop = true;
        // reset the sessionID to null
        Global.sessionid = "";

        // toast: current session has timed out
        Toast.makeText(globalvars, "Current session has timed out.", Toast.LENGTH_SHORT).show();

        // go back to the login screen
        Intent toLogin = new Intent(this, LoginActivity.class);
        toLogin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(toLogin);
        finish();
    }

}
